package com.csist.util;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @ClassName JSONUtil
 * @Description json字符串处理工具类
 * @Author
 * @Date 2024/6/18 上午8:29
 * @Version 1.0
 */
public class JSONUtil {

    private JSONUtil() {
    }

    /**
     * 从请求获取JSON字符串
     *
     * @param request 请求对象
     * @return JSON字符串
     * @throws IOException
     */
    public static String getJSON(HttpServletRequest request) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
        StringBuilder jsonsb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            jsonsb.append(line);
        }
        br.close();
        return jsonsb.toString();
    }

    /**
     * 从请求中获取JSON对象
     *
     * @param request 请求对象
     * @return JSON对象
     * @throws IOException
     */
    public static JSONObject getJSONObject(HttpServletRequest request) throws IOException {
        return JSON.parseObject(getJSON(request));
    }

    /**
     * 从字符串中解析JSON对象
     *
     * @param json JSON字符串
     * @return JSON对象
     * @throws IOException
     */
    public static JSONObject getJSONObject(String json) throws IOException {
        return JSON.parseObject(json);
    }

    /**
     * 从请求中获取JSON数组
     *
     * @param request 请求对象
     * @return JSON数组
     * @throws IOException
     */
    public static JSONArray getJSONArray(HttpServletRequest request) throws IOException {
        return JSON.parseArray(getJSON(request));
    }

    /**
     * 从字符串中解析JSON数组
     *
     * @param json JSON字符串
     * @return JSON数组
     * @throws IOException
     */
    public static JSONArray getJSONArray(String json) throws IOException {
        return JSON.parseArray(json);
    }

    /**
     * 将对象转化为JSON字符串
     *
     * @param object 任意对象
     * @return JSON字符串
     */
    public static String toJSON(Object object) {
        return JSON.toJSONString(object);
    }
}
